# -*- coding: utf-8 -*-
###################################################################################
#   
#    Copyright (C) 2019 RedTN 
# 
#此程序是自由软件：您可以根据自由软件基金会发布的GNU Affero通用公共许可证（许可证的第3版或（由您选择）任何更高版本）的条款重新分发和/或修改它。
#这个程序是分发的，希望它是有用的，但没有任何保证；甚至没有隐含的保证适销性或适合特定用途。有关详细信息，请参阅GNU Affero通用公共许可证。
#
#您应该已经收到GNU Affero通用公共许可证的副本以及此程序。如果没有，请参见<http://www.gnu.org/licenses/>。#
###################################################################################

import logging

from odoo import models, api, fields

_logger = logging.getLogger(__name__)

class Stage(models.Model):
    
    _name = "hr_official_docs.userstage"
    _inherit = ['mail.thread']
    _description = "User Stage"
    _order = "sequence"
    _sql_constraints = [
        ('sequence_unique', 'unique(create_uid,template_id,sequence)', 'Please enter a unique sequence.'),
    ]
    
    #===========================================================================
    # Variables
    #===========================================================================
    
    name = fields.Char(
        #required=True,
        translate=True
    )
    
    document_ids = fields.One2many(
        "hr_official_docs.document",
        "stage_id",
    )
    
    stage_id = fields.Many2one(
        "hr_official_docs.stage",
        string="Stage",
        ondelete="RESTRICT",
        default=lambda r: r.env["hr_official_docs.stage"].get_first_stage(),
    )
    template_id = fields.Many2one(
        "hr_official_docs.usertemplate",
        "User Template",
        ondelete="cascade"
    )
    
    sequence = fields.Integer(
        required=True,
        copy=False,
        readonly = True,
    )
    
    next_stage_id = fields.Many2one(
        "hr_official_docs.userstage",
        #compute="_compute_next_stage_id",
        #store = True,
    )
    
    prev_stage_id = fields.Many2one(
        "hr_official_docs.userstage",
        #compute="_compute_prev_stage_id",
        #store=True,
    )
    operator =fields.Many2one(
        'res.users',
        string ='operator at this stage',
        default=lambda self: self.env.user
    )
    #next_stage_group = fields.Many2one('hr_official_docs.groups')
    #prev_stage_group = fields.Many2one('hr_official_docs.groups')
    #next_stage_group = fields.Boolean()
    #prev_stage_group = fields.Boolean()
    
    #has_read_access_for_users = fields.Boolean(default=True)
    #has_read_access_for_directors = fields.Boolean()
    #has_read_access_for_managers = fields.Boolean()
    
    #has_write_access_for_users = fields.Boolean(default=True)
    #has_write_access_for_directors = fields.Boolean()
    #has_write_access_for_managers = fields.Boolean()

    #iscompleted = fields.Boolean()
    #===========================================================================
    # Computed Functions
    #===========================================================================
    
    @api.onchange('operator')
    def _compute_next_stage_id(self):
        '''for record in self:
            next_stage = self.search([("template_id", "=", record.template_id.id),("operator", "!=", False),("sequence", ">", record.sequence)])
            if next_stage:
                record.next_stage_id = next_stage[0]
            else:
                record.next_stage_id = False

        '''
        #self.sudo().write({'operator':self.operator.id})
        next_id = False
        i=1
        for re in  self.env['hr_official_docs.userstage'].search([('template_id','=',self.template_id.id)], order='sequence  ASC'):
            if i>1 and re.sequence == self.sequence:
                if self.operator:
                    next_id.write({'next_stage_id':re.id})
                else:
                    re.write({'next_stage_id': False})
                    next_id.write({'next_stage_id': False})
            elif i>1:
                if re.operator:
                    next_id.write({'next_stage_id': re.id})
                else:
                    next_id.write({'next_stage_id': False})
            if (re.sequence != self.sequence and re.operator) or (self.operator and re.sequence == self.sequence):
                next_id = re
            i+=1

    @api.onchange('operator')
    def _compute_prev_stage_id(self):
        '''for record in self:
            prev_stage = self.sudo().search([("template_id", "=", record.template_id.id),("operator", "!=", False),("sequence", "<", record.sequence)])
            if prev_stage:
                record.prev_stage_id = prev_stage[0]
            else:
                record.prev_stage_id = False
        '''
        #self.sudo().write({'operator':self.operator.id})
        prev_id = False
        i=1
        for re in  self.env['hr_official_docs.userstage'].search([('template_id','=',self.template_id.id)], order='sequence  ASC'):
            if i>1 and  re.sequence == self.sequence:
                if self.operator:
                    re.write({'prev_stage_id': prev_id.id})
                else:
                    re.write({'prev_stage_id': False})
            elif i>1:
                if re.operator:
                    re.write({'prev_stage_id':prev_id.id})
                else:
                    re.write({'prev_stage_id': False})
            if (re.sequence != self.sequence and re.operator) or (self.operator and re.sequence == self.sequence):
                prev_id = re
            i+=1




            '''if i>1 and (re.operator or (self.operator and re.sequence == self.sequence)):
                re.write({'prev_stage_id':prev_id.id})
            elif i>1 and re.operator and (not self.operator) and (re.sequence == self.sequence):
                re.write({'prev_stage_id':False})
            if re.operator:
                prev_id=re
            i+=1'''


    #===========================================================================
    # Global Helper Functions
    #===========================================================================
    
    @api.model
    def get_first_stage(self,template_id):
        if template_id:
            records = self.search([('create_uid', '=', self.env.user.id),("template_id", "=", template_id)])
        else:
            records = self.search([('create_uid', '=', self.env.user.id)])

        if records:
            return records[0]
        else:
            return False

    @api.model
    def get_last_stage(self):
        records = self.search([('create_uid', '=', self.env.user.id),("template_id", "=", self.template_id.id)])
        if records:
            return records[-1]
        else:
            return False

